package com.nbsaas.lbs.qq.v1.service;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
import com.nbsaas.http.Connection;
import com.nbsaas.http.HttpConnection;
import com.nbsaas.lbs.qq.v1.builder.ServicesBuilder;
import com.nbsaas.lbs.qq.v1.domain.response.Geo;

import java.io.IOException;

public class GeoCoderService extends BaseService{
  
  public GeoCoderService(String key) {
    super(key);
  }
  
  public Geo address(String address) {
    Geo result = new Geo();
    Connection connection = HttpConnection.connect("https://apis.map.qq.com/ws/geocoder/v1/");
    connection.data("key", key);
    connection.data("address", address);
    connection.method(Connection.Method.POST);
    try {
      String body = connection.execute().body();
      JsonParser parser = new JsonParser();
      JsonElement root = parser.parse(body);
      Gson gson = new Gson();
      result = gson.fromJson(root.getAsJsonObject().get("result").toString(), Geo.class);
      JsonElement component = root.getAsJsonObject().get("result").getAsJsonObject().get("address_components");
      if (component != null) {
        result.setProvince(component.getAsJsonObject().get("province").getAsString());
        result.setCity(component.getAsJsonObject().get("city").getAsString());
        result.setDistrict(component.getAsJsonObject().get("district").getAsString());
        result.setStreet(component.getAsJsonObject().get("street").getAsString());
        result.setStreetNumber(component.getAsJsonObject().get("street_number").getAsString());
        
      }
      System.out.println(body);
    } catch (IOException e) {
      e.printStackTrace();
    }
    return result;
  }
  
  public static void main(String[] args) {
    
    GeoCoderService service = ServicesBuilder.newBuilder().key("H4DBZ-WLVCU-YLEVF-4MIDF-MGB5H-TOFDR").build().geoGeoCoderService();
    Geo geo = service.address("北京市海淀区彩和坊路海淀西大街74号");
    System.out.println(geo);
  }
}
